package com.example.fourinarow;

import com.example.fourinarow.bluetooth.BluetoothConnection;
import com.example.fourinarow.bluetooth.DeviceListActivity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

//Class with activity to allow players to find opponents.
public class MPlobby extends Activity {

	private int player = 1;

	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;

	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";

	private static final int REQUEST_CONNECT_DEVICE = 1;
	private static final int REQUEST_ENABLE_BT = 2;
	private static final int END_GAME = 3;

	private String mConnectedDeviceName = null;

	private BluetoothAdapter mBluetoothAdapter = null;

	private BluetoothConnection mConnection = null;

	@Override
	// Prepare activity view and bluetooth adapter.
	// Start bluetooth connection and start listening for incoming connections.
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.lobby);
		Button scanButton = (Button) findViewById(R.id.button_scan);
		scanButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				player = 2;
				scan();
			}
		});

		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "Hittar inga bluetoothenheter.",
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}

		if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
			Intent discoverableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(
					BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(discoverableIntent);
		}
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);

		} else {
			mConnection = new BluetoothConnection(this, mHandler);
			MPgui.mConnection = mConnection;
		}
		if (mConnection != null) {
			if (mConnection.getState() == BluetoothConnection.STATE_NONE) {
				mConnection.start();
			}
		}

	}
//Method for launching activity in which to find bluetooth devices.
	public void scan() {
		Intent scanIntent = new Intent(this, DeviceListActivity.class);
		startActivityForResult(scanIntent, REQUEST_CONNECT_DEVICE);

	}

//Method for handling activity results from other activities.
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE:
			if (resultCode == Activity.RESULT_OK) {

				String address = data.getExtras().getString(
						DeviceListActivity.EXTRA_DEVICE_ADDRESS);
				BluetoothDevice device = mBluetoothAdapter
						.getRemoteDevice(address);
				mConnection.connect(device);
			}
			break;
		case REQUEST_ENABLE_BT:
			if (resultCode == Activity.RESULT_OK) {
				mConnection = new BluetoothConnection(this, mHandler);
			} else {
				Toast.makeText(this, "Bluetooth ej aktiverat.",
						Toast.LENGTH_SHORT).show();
				finish();
			}
			break;
		case Activity.RESULT_CANCELED:
			player = 1;
			break;
		case END_GAME:
			finish();
		}
	}

//Eventhandler for the bluetooth connection.
	public final Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.i("lobbyHandler", "case");
			switch (msg.what) {
			case MESSAGE_STATE_CHANGE:
				switch (msg.arg1) {
				//A connections has been established. Launch game with current players.
				case BluetoothConnection.STATE_CONNECTED:
					Intent mpIntent = new Intent(MPlobby.this, MPgui.class);
					mpIntent.putExtra("player", player);
					startActivityForResult(mpIntent, END_GAME);
					break;
				}
				break;
			//A bluetooth device has been chosen by the user. Notify user that a connection has been made.
			case MESSAGE_DEVICE_NAME:
				mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
				Toast.makeText(getApplicationContext(),
						"Ansluter till" + mConnectedDeviceName,
						Toast.LENGTH_SHORT).show();
				break;
			//A message has been sent from the bluetooth connection. Show the message to the user with a toast.
			case MESSAGE_TOAST:
				Toast.makeText(getApplicationContext(),
						msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
						.show();
				break;
			//A message has been received from the other player. Send the message as a broadcast to the MPgui.
			case MESSAGE_READ:
				byte[] readBuf = (byte[]) msg.obj;
				Intent in = new Intent();
				in.setAction("com.example.fourinarow.COMMUNICATION");
				in.putExtra("position", (int) readBuf[3]);
				MPgui.context.sendBroadcast(in);
			}
		}
	};

}
